
Ext.namespace('mapfish.widgets');

mapfish.widgets.Query = function(config){
    Ext.apply(this, config);
    mapfish.widgets.Query.superclass.constructor.call(this);
}

Ext.extend(mapfish.widgets.Query, Ext.Container, {
   
    /**
    * Property: mainTemplate
    *     The html template the widget is assigned to.
    */
    mainTemplate: new Ext.Template(
        '<div style="margin:10px 5px 5px 5px">', 
        '<table width=100% border="0">',
        '<tr><td><input type="text" id="nummer" size="15"/></td> <td><input type="text" id="schicht" size="15"/></td></tr>',
        '<tr><td><br></td><td></td></tr> <tr><td colspan="2"><div id="layerGridDiv" style="overflow:auto;   border:0px solid #00FF00;"></div></td></tr>',
        '</table>', 
        '<br>', 
        '<br>', 
        '<table width=100% border="0">',
        '<tr><td style="font-size:12px; height:30px">Add selection to map:</td> <td><div id="btnAdd" ></div></td></tr>',
        '<tr><td style="font-size:12px; height:30px">Clear map:</td> <td><div id="btnClrMap" ></div></td></tr>',
        '<tr><td style="font-size:12px; height:30px">Clear table:</td> <td><div id="btnClrTable" ></div></td></tr>',
        '</table>', 
        '</div>'),
        
        
        
    

    /**
    * Method: initComponent
    *    Inits the component
    */
    initComponent: function(){
    
    },
    
    /**
    * Method: updateGrid
    *    Adds records to the grid.
    * 
    * Parameters:
    * myStore {Ext.data.Store} 
    * myGrid {Ext......}
    */
    updateGrid: function(myTmpStore, myStore){
                
        var myFlag = 0;
        for (var i = 0; i < myTmpStore.getTotalCount(); i++) {
		for(var j = 0; j < myStore.getCount(); j++) {
			if(myStore.getAt(j).get('id') == myTmpStore.getAt(i).get('id')){ 
				myFlag = 1;
			}
		}
		if(myFlag == 0) {
			myStore.insert(0, myTmpStore.getAt(i));
		}
        }
    },
    
    /**
    * Method: addToMap
    *    Adds the selected features (as wms request) to the map.
    * 
    * Parameters:
    * myRecords {array .. Ext.data.Record} 
    */
    addToMap: function(myRecords){
	if(!myRecords.length) return;
	
	var myFeatureIds = '';
	
	for (var i=0; i<myRecords.length; i++) {
		myFeatureIds = myFeatureIds +  myRecords[i].get('id')  + ",";
	}
	
	myFeatureIds = myFeatureIds.substring(0,myFeatureIds.length-1);

        var walls = new OpenLayers.Layer.WMS("Walls",    
	"http://localhost:8080/geoserver/wms", {
	    srs: 'EPSG:21781',
	    FEATUREID: myFeatureIds,
	    layers: 'caa:walls',
	    transparent: 'true',
	    format: 'image/png'
	}, {
	    singleTile: true
	});
	walls.isBaseLayer = false;
	this.map.addLayers([walls]);
    },    
   
   
    /**
    * Method: removeLayersFromMap
    *    Removes all the manually added layers from the map.
    * 
    */
    removeLayersFromMap: function(){
	var myLayers = this.map.getLayersByName("Walls");
	for(var i=0; i<myLayers.length; i++) {
		this.map.removeLayer(myLayers[i]);
	}
    },    
    
    
    // private
    onRender: function(container, position){
        if (!this.el) {
            this.el = document.createElement('div');
        }
        mapfish.widgets.Query.superclass.onRender.apply(this, arguments);
        
        this.mainTemplate.overwrite(this.el, {});
        
        // all available house no.
        var store1 = new Ext.data.Store({
            //proxy: new Ext.data.HttpProxy({url: 'http://srsofaioi12288/cgi-bin/proxy.cgi?url=http%3A//srsofaioi12288%3A8080/geoserver/wfs%3Fservice%3Dwfs%26version%3D1.1.0%26request%3Dgetfeature%26typename%3Dtopp%3Ageo_bezirk_v%26maxfeatures%3D130%26outputformat%3Djson%26propertyname%3Dbzrk_name%2Cbzrk_nr'}),
            proxy: new Ext.data.HttpProxy({
                url: 'http://localhost/cgi-bin/proxy.cgi?url=http%3A//localhost%3A8080/geoserver/wfs%3Fservice%3Dwfs%26version%3D1.1.0%26request%3Dgetfeature%26typename%3Dcaa%3Awalls_v_house%26maxfeatures%3D300%26outputformat%3Djson%26propertyname%3Dhouse'
            }),
            sortInfo: {
                field: "house",
                direction: "ASC"
            },
            reader: new Ext.data.JsonReader({
                root: 'features'
            }, [{
                id: 'id'
            }, {
                name: 'house',
                mapping: 'properties["house"]'
            }])
        });
        
        
        // all available occupation-levels
        var store2 = new Ext.data.Store({
            //proxy: new Ext.data.HttpProxy({url: 'http://srsofaioi12288/cgi-bin/proxy.cgi?url=http%3A//srsofaioi12288%3A8080/geoserver/wfs%3Fservice%3Dwfs%26version%3D1.1.0%26request%3Dgetfeature%26typename%3Dtopp%3Ageo_bezirk_v%26maxfeatures%3D130%26outputformat%3Djson%26propertyname%3Dbzrk_name%2Cbzrk_nr'}),
            proxy: new Ext.data.HttpProxy({
                url: 'http://localhost/cgi-bin/proxy.cgi?url=http%3A//localhost%3A8080/geoserver/wfs%3Fservice%3Dwfs%26version%3D1.1.0%26request%3Dgetfeature%26typename%3Dcaa%3Awalls_v_phase%26maxfeatures%3D300%26outputformat%3Djson%26propertyname%3Dphase'
            }),
            sortInfo: {
                field: "phase",
                direction: "ASC"
            },
            reader: new Ext.data.JsonReader({
                root: 'features'
            }, [{
                id: 'id'
            }, {
                name: 'phase',
                mapping: 'properties["phase"]'
            }])
        });
        
        
        // selects mauerzuege where house_no = store1.house_no
        var store3 = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: 'http://localhost/cgi-bin/proxy.cgi?url=http%3A//localhost%3A8080/geoserver/wfs%3Fservice%3Dwfs%26version%3D1.1.0%26request%3Dgetfeature%26typename%3Dcaa%3Awalls%26maxfeatures%3D300%26outputformat%3Djson%26propertyname%3Dwall%2Chouse%2Cphase'
            }),
            sortInfo: {
                field: "wall",
                direction: "DESC"
            },
            reader: new Ext.data.JsonReader({
                root: 'features'
            }, [{
                id: 'id'
            }, {
                name: 'id'
            },{
                name: 'phase',
                mapping: 'properties["phase"]'
            }, {
                name: 'house',
                mapping: 'properties["house"]'
            }, {
                name: 'wall',
                mapping: 'properties["wall"]'
            }])
        });



        // grid store
        var store5 = new Ext.data.SimpleStore({
            fields: ['id', 'wall', 'house', 'phase']
            
        });
        
        
        
        // house no combobox
        var combo1 = new Ext.form.ComboBox({
            hiddenName: 'hausnummer',
            store: store1,
            displayField: 'house',
            valueField: 'house',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            emptyText: 'House No...',
            selectOnFocus: true,
            applyTo: 'nummer'
        });
        
        
        // occupation levels combobox
        var combo2 = new Ext.form.ComboBox({
            hiddenName: 'bauschicht',
            store: store2,
            displayField: 'phase',
            valueField: 'phase',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            emptyText: 'Level...',
            selectOnFocus: true,
            applyTo: 'schicht'
        });        
        
        combo1.store.load();
        combo2.store.load();
        
        combo1.on('select', function(){
            var hausnummer = Ext.get("hausnummer").getValue();
            store3.proxy = new Ext.data.HttpProxy({
                url: 'http://localhost/cgi-bin/proxy.cgi?url=http%3A//localhost%3A8080/geoserver/wfs%3Fservice%3Dwfs%26version%3D1.1.0%26request%3Dgetfeature%26typename%3Dcaa%3Awalls%26maxfeatures%3D300%26outputformat%3Djson%26propertyname%3Dwall%2Chouse%2Cphase%26cql_filter%3Dhouse%3D' + hausnummer
            });
            store3.load();
        });
        

        combo2.on('select', function(){
            var schicht = Ext.get("bauschicht").getValue();
            store3.proxy = new Ext.data.HttpProxy({
                url: 'http://localhost/cgi-bin/proxy.cgi?url=http%3A//localhost%3A8080/geoserver/wfs%3Fservice%3Dwfs%26version%3D1.1.0%26request%3Dgetfeature%26typename%3Dcaa%3Awalls%26maxfeatures%3D300%26outputformat%3Djson%26propertyname%3Dwall%2Chouse%2Cphase%26cql_filter%3Dphase%3D' + schicht
            });
            store3.load();
        });
        
        store3.on('load', function(){
            this.updateGrid(store3, store5);
        },this);        
        

        // *** create the layer grid

	 var sm = new Ext.grid.CheckboxSelectionModel();
       
 
     // create the editor grid
     var grid = new Ext.grid.GridPanel({
         id: 'gridId',
         store: store5,
          sm: sm,

         columns: [
             sm,
             {id:'common', header: "Wall", dataIndex: 'wall', sortable: true},
             {header: "House", dataIndex: 'house', sortable: true},
             {header: "Level", dataIndex: 'phase', sortable: true}
         ],
         renderTo: 'layerGridDiv',
         //width:300,
         height:200,
         autoExpandColumn:'common',
         //title:'Edit Plants?',
         frame:false
     });
 

        var add_button = new Ext.Button({
            text: 'OK',
            applyTo: 'btnAdd'
        });
        
        add_button.on('click', function(){
             var selRec = Ext.getCmp('gridId').getSelectionModel().getSelections();
             this.addToMap(selRec);
        }, this);

 
        var clearMap_button = new Ext.Button({
            text: 'OK',
            applyTo: 'btnClrMap'
        });
        
        clearMap_button.on('click', function(){
	    this.removeLayersFromMap();
        }, this); 
        
        var clearTable_button = new Ext.Button({
            text: 'OK',
            applyTo: 'btnClrTable'
        });
        
        clearTable_button.on('click', function(){
             Ext.getCmp('gridId').getStore().removeAll();
        }, this);         

    }    
    
    
    
    
    
    
    
    
    
});

Ext.reg('query', mapfish.widgets.Query);

